<template>
  <div v-loading.fullscreen="loading">
    <el-row :gutter="10">
      <el-col
        :span="12"
        style="text-align: left;"
      >
        <el-button
          type="success"
          @click="addBtnClick"
        >添加</el-button>
        <el-input
          style="display:inline;margin: 0px 12px"
          v-model="tableDatas.filters.searchText"
          clearable
        >
          <template #prepend>搜索</template>
        </el-input>
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogDatas.dialogFormVisible"
      :title="dialogDatas.isNew ? '添加':'修改'"
      destroy-on-close
      top="5vh"
    >
      <el-scrollbar max-height="70vh">
        <el-form :model="dialogDatas.currentData">
          <el-form-item
            v-for="item in dialogDatas.formItems"
            :label="item.label"
          >
            <div v-if="item.isDate">
              <el-date-picker
                v-model="dialogDatas.currentData[item.value]"
                :type="item.dateOption ? item.dateOption.type : 'date'"
                :format="item.dateOption ? item.dateOption.format : 'YYYY/MM/DD'"
                :value-format="item.dateOption ? item.dateOption.valueFormat : 'YYYY/MM/DD'"
                :date-format="item.dateOption ? item.dateOption.dateFormat : ''"
                :time-format="item.dateOption ? item.dateOption.timeFormat : ''"
                :disabled="item.disable"
              />
            </div>

            <div
              v-else-if="item.isSelect"
              style="width: 100%"
            >
              <el-select
                v-model="dialogDatas.currentData[item.value]"
                :disabled="item.disable"
                filterable
              >
                <el-option
                  v-for="item in item.selectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>

            <div
              v-else-if="item.isImg"
              style="width: 100%"
            >
              <FileUploadVue
                :src="dialogDatas.currentData['FULL_URL'] ? (dialogDatas.currentData['FULL_URL'] + `?t=${Date.now()}`) :''"
                @fileSelected="item.fileSelected"
              >
              </FileUploadVue>
            </div>

            <div v-else-if="item.isSwitch">
              <el-switch
                v-model="dialogDatas.currentData[item.value]"
                inline-prompt
                :active-text="item.trueValue"
                :inactive-text="item.falseValue"
                :active-value="item.trueValue"
                :inactive-value="item.falseValue"
                :disabled="item.disable"
                size="large"
              />
            </div>
            <div
              v-else
              style="width: 100%"
            >
              <el-input
                v-model="dialogDatas.currentData[item.value]"
                :disabled="item.disable"
              />
            </div>
          </el-form-item>
        </el-form>
      </el-scrollbar>

      <template #footer>
        <span>
          <el-button @click="dialogDatas.dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogDatas.confirmBtnClick"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-table
      class="marginTop10"
      :data="tableDatas.tableDatasAfterPage"
      stripe
      border
      empty-text="无数据"
      max-height="80vh"
    >
      <el-table-column
        v-for="column in tableDatas.tableColumns"
        :type="column.type"
        :prop="column.prop"
        :label="column.label"
        :align="column.align"
        :width="column.width"
      >

        <template
          #default="scope"
          v-if="column.prop =='URL'"
        >
          <div>
            <div v-if="scope.row.FULL_URL">
              <img
                style="width: 200px;height:100px"
                :src="scope.row.FULL_URL + `?t=${Date.now()}`"
              >
            </div>
            <div v-else>暂无图片</div>
          </div>
        </template>

        <!-- <template
          #default="scope"
          v-if="column.prop =='TYPE'"
        >
          <div>
            <el-checkbox
              v-model="scope.row.TYPE"
              true-value="固定"
              false-value="不固定"
              label="固定"
              size="large"
            />
          </div>
        </template> -->

        <template
          #default="scope"
          v-if="column.prop =='operate'"
        >
          <div>
            <el-button
              type="success"
              @click="tableDatas.editBtnClick(scope.row)"
            >修改</el-button>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              title="确定删除该条记录?"
              @confirm="tableDatas.deleteBtnClick(scope.row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- <el-pagination
      class="marginTop10"
      @size-change="tableDatas.filters.handleSizeChange"
      @current-change="tableDatas.filters.handleCurrentChange"
      :page-sizes="[10, 15, 20, 100]"
      :page-size="tableDatas.filters.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableDatas.tableDatasAfterFilter.length"
    >
    </el-pagination> -->

  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { onMounted, watch } from '@vue/runtime-core';
import { v4 } from 'uuid';
import myAxios from '@/myAxios/myAxios';
import { show, showSuccess, showWarning } from '@/hooks/useMyMessageBox';
import FileUploadVue from '@/components/FileUpload.vue';

export default {
  name: '',
  components: {
    FileUploadVue
  },

  setup () {
    let loading = ref(false);
    let addBtnClick = function () {
      showFormDialog();
    };

    let showFormDialog = function (row) {
      if (row) {
        dialogDatas.isNew = false;
        dialogDatas.currentData = { ...row };
      }
      else {
        dialogDatas.isNew = true;
        dialogDatas.currentData = {};
      }
      dialogDatas.dialogFormVisible = true;
    };

    let dialogDatas = reactive({
      dialogFormVisible: false,
      currentData: {},
      isNew: false,
      formItems: [
        // {
        //   "value": "CD_ID",
        //   "label": "菜品ID",
        //   "isDate": false
        // },
        {
          "value": "NAME",
          "label": "菜品名",
          "isDate": false,
          "disable": true,
        },
        {
          "value": "PRICE",
          "label": "价格",
          "isDate": false
        },
        {
          "value": "URL",
          "label": "图片地址",
          "isDate": false,
          "isImg": true,
          "fileSelected": function (event) {
            if (event) {
              dialogDatas.currentData.NEW_URL = event.target.files[0];
            }
            else {
              dialogDatas.currentData.NEW_URL = undefined;
            }
          },
        },
        {
          "value": "DESCRIPTION",
          "label": "描述",
          "isDate": false
        },
        {
          "value": "TYPE",
          "label": "是否为固定每日菜单",
          "isDate": false,
          "isSwitch": true,
          "trueValue": "固定",
          "falseValue": "不固定",
        },
        // {
        //   "value": "EMP_DEPARTMENT",
        //   "label": "部门",
        //   "isDate": false,
        //   "disable": false,
        //   "isSelect": true,
        //   "selectOptions": [
        //     {
        //       "value": "value_1",
        //       "label": "label_1"
        //     },
        //     {
        //       "value": "value_2",
        //       "label": "label_2"
        //     }
        //   ]
        // },
        // {
        //   "value": "DATE_TIME",
        //   "label": "精确到秒的时间(示例,可删除)",
        //   "isDate": true,
        //   "dateOption": {
        //     "type": "datetime",
        //     "format": "YYYY/MM/DD HH:mm:ss",
        //     "dateFormat": "YYYY/MM/DD",
        //     "timeFormat": "HH:mm:ss",
        //     "valueFormat": "YYYY/MM/DD HH:mm:ss"
        //   }
        // },
      ],
      confirmBtnClick: async function () {
        loading.value = true;
        let row = dialogDatas.currentData;
        let CD_ID = row.CD_ID ? row.CD_ID : v4();
        let NAME = row.NAME;
        let filename = `${CD_ID}-${NAME}.jpeg`;

        let uploadResult = ``;
        if (!row.NEW_URL) {
          uploadResult = '未上传图片!';
        }
        else if (row.NEW_URL != row.URL) {
          uploadResult = await dialogDatas.uploadFile(row.NEW_URL, filename);
        }
        else {
          uploadResult = '未修改图片,成功!';
        }
        if (uploadResult.includes('成功')) {

          let params = `${CD_ID}\t${NAME}\t${row.PRICE}`
            + `\t${filename}\t${row.DESCRIPTION}\t${row.TYPE}`;
          let res = await myAxios.post('陈帅廷添加或修改食堂菜单信息', params);
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            showSuccess('提交成功!' + res);
            getTableDatas();
          }
          else {
            loading.value = false;
            showWarning('更新失败res!' + res);
          }
        }
        else {
          loading.value = false;
          showWarning('图片上传失败err!' + uploadResult);
        }

      },
      uploadFile: function (file, filename) {
        return new Promise((resolve, reject) => {
          var reader = new FileReader();
          reader.onload = async (e) => {
            // let filename = `${`test`}.jpeg`;D:\WebSite\HTML5MES\QDMES
            // let filePath = `D:\\QDMES\\CHER\\driver_order_menu\\img\\menu\\`;
            let filePath = `D:\\WebSite\\HTML5MES\\QDMES\\`;
            let result = await myAxios.uploadFile(e.target.result, filePath, filename);
            if (result.includes('成功')) {
              resolve('上传成功');
            }
            else {
              resolve('上传失败' + result);
            }
          };
          reader.readAsDataURL(file);

        });
      },
      cancelBtnClick: function () {

      }
    });

    let getTableDatas = function () {
      loading.value = true;

      let params = ``;
      myAxios.get('陈帅廷查询食堂可用菜单', params).then(res => {
        if (res instanceof Array) {
          loading.value = false;
          res.forEach(el => {
            el.NEW_URL = el.URL;
            if (el.URL) {
              el.FULL_URL = `http://htqdds.haitian.com:9911/qdmes/CHER/driver_order_menu/img/menu/` + el.URL;
            }
            else {
              el.FULL_URL = ``;
            }
          });
          tableDatas.oritableData = [...res];
          //   showSuccess('最新数据获取成功!');
        }
        else {
          loading.value = false;
          showWarning('获取数据失败res!' + res);
        }
      }).catch((err) => {
        loading.value = false;
        showWarning('获取数据失败err!' + err);
      });
    };

    onMounted(() => {
      getTableDatas();
    });

    let searchKeys = ['NAME', 'DESCRIPTION'];
    let tableDatas = reactive({
      //表格筛选展示相关代码
      filters: {
        searchText: '',

        //表格翻页相关代码
        currentPage: 1,
        pagesize: 10,
        handleSizeChange (val) {
          tableDatas.filters.pagesize = val;
        },
        handleCurrentChange (val) {
          tableDatas.filters.currentPage = val;
        },
      },
      tableDatasAfterFilter: computed(() => {
        let fData = tableDatas.oritableData;

        if (tableDatas.filters.searchText) {
          let searchText = tableDatas.filters.searchText;
          fData = fData.filter(item => {
            return searchKeys.some(key => {
              return String(item[key]).toLowerCase().includes(searchText.toLowerCase());
            });
          });
        }

        return fData;
      }),
      tableDatasAfterPage: computed(() => {
        let fData = tableDatas.tableDatasAfterFilter;
        // fData = fData.slice((tableDatas.filters.currentPage - 1) * tableDatas.filters.pagesize, tableDatas.filters.currentPage * tableDatas.filters.pagesize);
        return fData;
      }),

      tableColumns: [
        {
          "type": "index",
          "prop": "",
          "label": "序号",
          "align": "center",
          "width": 60
        },
        // {
        //   "prop": "CD_ID",
        //   "label": "菜品ID",
        //   "align": "center"
        // },
        {
          "prop": "NAME",
          "label": "菜品名",
          "align": "center"
        },
        {
          "prop": "PRICE",
          "label": "价格",
          "align": "center"
        },
        {
          "prop": "URL",
          "label": "图片地址",
          "align": "center"
        },
        {
          "prop": "DESCRIPTION",
          "label": "备注",
          "align": "center"
        },
        {
          "prop": "TYPE",
          "label": "是否为固定每日菜单",
          "align": "center"
        },
        {
          "prop": "operate",
          "label": "操作",
          "align": "center",
          "width": 170
        }
      ],
      oritableData: [
        {
          "CD_ID": "1",
          "NAME": "水煮肉片",
          "PRICE": 22,
          "URL": "1-水煮肉片.jpeg",
          "DESCRIPTION": "麻辣鲜香，嫩滑多汁，经典川菜。\n\n",
          "TYPE": null
        },
      ],
      editBtnClick: function (row) {
        showFormDialog(row);
      },
      deleteBtnClick: function (row) {
        loading.value = true;
        let CD_ID = row.CD_ID;

        // let json = `{"CD_ID":"587639ea-d7fd-4b9b-b493-2131db2f3f68","NAME":"手工小馄饨","PRICE":6,"URL":"587639ea-d7fd-4b9b-b493-2131db2f3f68-手工小馄饨.jpeg","DESCRIPTION":"15个/盒，猪肉馅","TYPE":"固定","STATE":"可用"}`
        //   + `{"CD_ID":"587639ea-d7fd-4b9b-b493-2131db2f3f68","NAME":"手工小馄饨","PRICE":6,"URL":"587639ea-d7fd-4b9b-b493-2131db2f3f68-手工小馄饨.jpeg","DESCRIPTION":"15个/盒，猪肉馅","TYPE":"固定","STATE":"可用"}`;
        // let params = `${CD_ID}\t${1}\t${CD_ID}\t${json}`;
        let params = `${CD_ID}\t${'禁用'}`;
        // let name = `陈帅廷添加或修改菜单记录`;
        let name = `陈帅廷修改食堂菜单状态`;
        myAxios.post(name, params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            showSuccess('删除成功!' + res);
            // ElMessage({
            //   showClose: true,
            //   type: 'success',
            //   message: '删除成功!' + res
            // });
            tableDatas.oritableData.splice(tableDatas.oritableData.indexOf(row), 1);
          }
          else {
            loading.value = false;
            showWarning('删除失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('删除失败err!' + err);
        });

      },
    });

    return {
      loading,
      addBtnClick,
      dialogDatas,
      tableDatas
    };
  }
}
</script>
<style lang="css" scope>
.marginTop10 {
  margin-top: 10px;
}
</style>

